import { memo, ChangeEvent, useState, useEffect } from 'react'
import { Input } from 'antd'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { LIST_SEARCH_PARAM_KEY } from '@/constant'

const { Search } = Input

const ListSearch = memo(() => {
  const [searchValue, setSearchValue] = useState('')
  const [searchParams] = useSearchParams()

  const { pathname } = useLocation()
  const nav = useNavigate()

  const changeSearchValue = (event: ChangeEvent<HTMLInputElement>) => {
    setSearchValue(event.target.value)
  }

  //搜索
  const search = (value: string) => {
    nav(`${pathname}?${LIST_SEARCH_PARAM_KEY}=${value}`)
  }

  useEffect(() => {
    const curVal = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
    setSearchValue(curVal)
  }, [searchParams])

  return (
    <Search
      size="large"
      allowClear
      placeholder="请输入标题..."
      style={{ width: '260px' }}
      value={searchValue}
      onChange={e => changeSearchValue(e)}
      onSearch={search}
    />
  )
})

export default ListSearch
